package com.fish.anne.webapp.action;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.providers.encoding.PasswordEncoder;

import com.fish.anne.model.SystemAction;
import com.fish.anne.model.SystemAdminRole;
import com.fish.anne.model.SystemAdminUser;
import com.fish.anne.model.SystemRole;
import com.fish.anne.service.SystemActionManager;
import com.fish.anne.service.SystemAdminRoleManager;
import com.fish.anne.service.SystemAdminUserManager;
import com.fish.anne.service.SystemRoleManager;
import com.fish.anne.webapp.util.Pager;
import com.fish.anne.webapp.util.WebContextKey;
import com.opensymphony.xwork2.Preparable;

public class SystemAdminUserAction extends BaseAction implements Preparable {
	private SystemAdminUserManager systemAdminUserManager;
	private List<SystemAdminUser> systemAdminUsers;

	private List<SystemAction> systemActions;

	public List<SystemAction> getSystemActions() {
		return systemActions;
	}

	public void setSystemActions(List<SystemAction> systemActions) {
		this.systemActions = systemActions;
	}

	private SystemActionManager systemActionManager;

	public void setSystemActionManager(SystemActionManager systemActionManager) {
		this.systemActionManager = systemActionManager;
	}

	public List<SystemAdminUser> getSystemAdminUsers() {
		return systemAdminUsers;
	}

	public void setSystemAdminUsers(List<SystemAdminUser> systemAdminUsers) {
		this.systemAdminUsers = systemAdminUsers;
	}

	public List<SystemRole> getSystemRoles() {
		return systemRoles;
	}

	public void setSystemRoles(List<SystemRole> systemRoles) {
		this.systemRoles = systemRoles;
	}

	public SystemAdminUser getAdminUser() {
		return adminUser;
	}

	public void setAdminUser(SystemAdminUser adminUser) {
		this.adminUser = adminUser;
	}

	public Long getAdminId() {
		return adminId;
	}

	public void setAdminId(Long adminId) {
		this.adminId = adminId;
	}

	public void setSystemAdminUserManager(SystemAdminUserManager systemAdminUserManager) {
		this.systemAdminUserManager = systemAdminUserManager;
	}

	public void setSystemAdminRoleManager(SystemAdminRoleManager systemAdminRoleManager) {
		this.systemAdminRoleManager = systemAdminRoleManager;
	}

	public void setSystemRoleManager(SystemRoleManager systemRoleManager) {
		this.systemRoleManager = systemRoleManager;
	}

	private SystemAdminRoleManager systemAdminRoleManager;
	private List<SystemAdminRole> systemAdminRoles;

	private SystemRoleManager systemRoleManager;
	private List<SystemRole> systemRoles;

	private SystemAdminUser adminUser;
	private Long adminId;

	private PasswordEncoder passwordEncoder;

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	/**
	 * Grab the entity from the database before populating with request
	 * parameters
	 */
	public void prepare() {

		if (getRequest().getMethod().equalsIgnoreCase("post")) {
			// prevent failures on new
			String systemAdminUserId = getRequest().getParameter("systemAdminUser.adminId");
			if (systemAdminUserId != null && !systemAdminUserId.equals("")) {
				adminUser = systemAdminUserManager.get(new Long(systemAdminUserId));
			}
		}
	}

	public String list() {
		this.systemAdminUsers = this.systemAdminUserManager.getAll();
		return SUCCESS;
	}

	public String delete() {
		
		if (this.getAdminUser().getAdminSuper() != 1) {
			saveMessage("只有超级管理员才可以删除");
			return SUCCESS;
		}
		if (systemAdminUsers == null) {
			return SUCCESS;
		}
		for (SystemAdminUser admin : systemAdminUsers) {
			if (admin != null && admin.getAdminId() != null) {
				systemAdminUserManager.remove(admin.getAdminId());
			}
		}

		saveMessage(getText("systemAdminUser.deleted"));

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String login() {
		if (adminUser == null) {
			return INPUT;
		}
		if (adminUser.getUsername() == null || adminUser.getUsername().equals("")) {
			return INPUT;
		}
		if (adminUser.getUserpass() == null || adminUser.getUserpass().equals("")) {
			return INPUT;
		}
		adminUser = systemAdminUserManager.getByNameAndPassword(adminUser.getUsername(), adminUser.getUserpass());

		 
		if (adminUser == null || !adminUser.isStatus()) {
			loginError = "用户名或者密码错误,请重试";
			
			return INPUT;
		}
		session.put(WebContextKey.ADMIN_USER, adminUser);

		return SUCCESS;
	}
	private String loginError;

	public String getLoginError() {
		return loginError;
	}

	public void setLoginError(String loginError) {
		this.loginError = loginError;
	}

	/***
	 * load available nav
	 */
	@SuppressWarnings("unchecked")
	public String execute() {
		adminUser = super.getSystemAdminUser();
		if(adminUser == null){
			return INPUT;
		}
		systemActions = setActionLevel(systemActionManager.getAll());
		if (adminUser.getAdminSuper() != 1) {
			systemActions = initAvailableActions();
		}

		return SUCCESS;
	}

	private List<SystemAction> initAvailableActions() {
		List<SystemAction> limitActions = new ArrayList<SystemAction>();

		List<SystemAction> availableActions = this.systemActionManager.findAvailableActionByAdminId(super.getAdminUserId());

		for (SystemAction sa : systemActions) {

			for (SystemAction asa : availableActions) {
				if (sa.getActionId().equals(asa.getActionId())) {
					limitActions.add(sa);
					break;
				}
			}

		}

		return limitActions;
	}

	@SuppressWarnings("unchecked")
	public String savePassword() {
		SystemAdminUser currenctAdminUser = super.getSystemAdminUser();
		String old = adminUser.getOldPassword();
		old = passwordEncoder.encodePassword(old, null);
		if (!old.equals(currenctAdminUser.getUserpass())) {
			super.saveMessage("不一致");
			return INPUT;
		}
		String newp = adminUser.getUserpass();
		String comfirmp = adminUser.getUserpassComfirm();
		if (!newp.equals(comfirmp)) {
			super.saveMessage("不一致");
			return INPUT;
		}
		currenctAdminUser.setChangepwd(true);
		currenctAdminUser.setUserpass(newp);
		systemAdminUserManager.updateSystemAdminUserPassword(currenctAdminUser);
		super.saveMessage("");
		session.put(WebContextKey.ADMIN_USER, currenctAdminUser);
		super.saveMessage("修改成功");
		return SUCCESS;
	}

 

	public String desktop() {

		return SUCCESS;
	}

	public String edit() {
		systemRoles = this.systemRoleManager.getAll();

		if (adminId != null) {
			adminUser = systemAdminUserManager.get(adminId);
			this.systemAdminRoles = this.systemAdminRoleManager.findByAdminId(adminId);
			systemAdminRoles = format(systemAdminRoles, systemRoles);
		} else {
			adminUser = new SystemAdminUser();
			systemAdminRoles = format(new ArrayList<SystemAdminRole>(), systemRoles);
		}

		return SUCCESS;
	}

	public List<SystemAdminRole> getSystemAdminRoles() {
		return systemAdminRoles;
	}

	public void setSystemAdminRoles(List<SystemAdminRole> systemAdminRoles) {
		this.systemAdminRoles = systemAdminRoles;
	}

	public String save() throws Exception {

		boolean isNew = (adminUser.getAdminId() == null);
		if (isNew) {
			adminUser.init();
			if(systemAdminRoles==null || systemAdminRoles.isEmpty()){
				systemRoles = this.systemRoleManager.getAll();
				systemAdminRoles = format(new ArrayList<SystemAdminRole>(), systemRoles);
				return INPUT;
			}
		}else{
			if(systemAdminRoles==null || systemAdminRoles.isEmpty()){
				systemRoles = this.systemRoleManager.getAll();
				this.systemAdminRoles = this.systemAdminRoleManager.findByAdminId(adminUser.getAdminId());
				systemAdminRoles = format(systemAdminRoles, systemRoles);
				return INPUT;
			}
		}
		
		adminUser.setSystemAdminRoles(systemAdminRoles);
		systemAdminUserManager.save(adminUser);
 
		saveMessage("添加/修改成功.");

		return SUCCESS;

	}

	private List<SystemAdminRole> format(List<SystemAdminRole> now, List<SystemRole> srs) {
		List<SystemAdminRole> tbList = new ArrayList<SystemAdminRole>();

		for (SystemRole sr : srs) {
			SystemAdminRole sra = get(now, sr);
			tbList.add(sra);
		}

		return tbList;
	}

	private SystemAdminRole get(List<SystemAdminRole> now, SystemRole sr) {
		long roleId = sr.getRoleId();
		for (SystemAdminRole sar : now) {
			if (sar.getRoleId() == roleId) {
				sar.setRoleName(sr.getRoleName());
				return sar;
			}
		}
		SystemAdminRole sar = new SystemAdminRole();
		sar.setRoleId(roleId);
		sar.setRoleName(sr.getRoleName());

		return sar;
	}

	private List<SystemAction> setActionLevel(List<SystemAction> all) {
		List<SystemAction> top = new ArrayList<SystemAction>();
		for (SystemAction topAct : all) {
			if (topAct.getParentId().longValue() == 0) {
				top.add(topAct);
				List<SystemAction> topSub = new ArrayList<SystemAction>();
				topAct.setSubActions(topSub);
				for (int j = 0; j < all.size(); j++) {
					SystemAction secondAct = all.get(j);
					if (secondAct.getParentId().longValue() == topAct.getActionId()) {
						topSub.add(secondAct);

						List<SystemAction> secondSub = new ArrayList<SystemAction>();
						secondAct.setSubActions(secondSub);
						for (int i = 0; i < all.size(); i++) {

							SystemAction thiredAct = all.get(i);
							if (thiredAct.getParentId() == secondAct.getActionId().longValue()) {
								secondSub.add(thiredAct);
							}
						}

					}
				}
			}

		}
		return top;
	}

}